package com.corgi.mybatis.modules.controller;

import com.corgi.mybatis.modules.domain.Attachment;
import com.corgi.mybatis.modules.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @title: FileDownController
 * @description:
 * @author: dengmiao
 * @create: 2019-10-26 14:19
 **/
@Controller
public class FileDownController {

    @Autowired
    private AttachmentService attachmentService;

    @GetMapping("download")
    public void download(Long id, HttpServletResponse response) throws IOException {
        Attachment attachment = attachmentService.selectById(id);
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + attachment.getFileName());
        response.addHeader("Content-Length", "" + attachment.getFileSize());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        byte[] buffer = attachment.getFile();
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
}
